<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="450px"
      :before-close="closeDialog"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form
        :model="addForm"
        :rules="rules"
        ref="refForm"
        label-width="100px"
        inline
      >
        <!--  current === 'show' && current === 'password' && current === 'edit' -->
        <span v-if="current !== 'show' && current !== 'password'">
          <el-form-item size="small" label="手机号码" prop="mobile">
            <el-input
              style="width: 300px"
              clearable
              disabled
              v-model="addForm.mobile"
              placeholder="请输入"
              maxlength="11"
            ></el-input>
          </el-form-item>
          <el-form-item size="small" label="短信验证码" prop="smsCode">
            <el-input
              style="width: 300px"
              clearable
              v-model="addForm.smsCode"
              placeholder="请输入"
              maxlength="6"
            >
              <el-button slot="append" @click="smsCodeClick">
                <span v-show="showCountDown">获取验证码</span>
                <span v-show="!showCountDown">{{ countDown }}秒重新获取</span>
              </el-button></el-input
            >
          </el-form-item>
        </span>
        <el-form-item
          size="small"
          label="指令密码"
          prop="password"
          v-if="current"
        >
          <el-input
            v-model="addForm.password"
            :disabled="current === 'show'"
            :show-password="current === 'edit' || current === 'password'"
            clearable
            placeholder="请输入指令密码"
            size="small"
            style="width: 300px"
            maxlength="20"
            oninput="value=value.replace(/\s*/g,'')"
            readOnly
            autocomplete="off"
            @focus="onFocus"
            @blur="onBlur"
            @input.native="onInput($event, addForm.password)"
            @mousedown.native="onMousedown"
          >
          </el-input>
        </el-form-item>
      </el-form>

      <div class="tip" v-if="pageType && !statusInfo.cmdPasswordState">
        <span class="label">温馨提示：</span>
        您尚未设置指令密码。为确保安全，请先通过短信验证身份，再设置密码。完成后，即可使用指令远程管理设备。
      </div>
      <span slot="footer" class="dialog-footer" v-if="current !== 'show'">
        <el-button size="small" @click="closeDialog" class="cancel-button"
          >取 消</el-button
        >
        <el-button
          size="small"
          @click="submit"
          v-preventReClick="1000"
          class="confirm-button"
          >确 定</el-button
        >
      </span>
      <span slot="footer" class="dialog-footer" v-if="current === 'show'">
        <el-button
          size="small"
          @click="onEdit"
          v-preventReClick="1000"
          class="confirm-button"
          >编 辑</el-button
        >
        <el-button
          size="small"
          @click="closeDialog"
          v-preventReClick="1000"
          class="confirm-button"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getSmsCode,
  reqUtdQueryPassword,
  reqUtdSetPassword,
  reqKeyCommandSend,
} from "@api/api.js";
import {
  validateNumberLetter,
  validateNumber,
  validateNoChinese,
} from "@utils/validate";
import { mapState } from "vuex";

export default {
  props: ["pageType", "deviceInfo", "statusInfo", "handleType", "commandInfo"],
  components: {},
  data() {
    return {
      dialogVisible: false,

      current: "",
      title: "短信验证",

      addForm: {
        mobile: "",
        smsCode: "",
        password: "",
      },
      rules: {
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
        ],
        smsCode: [
          { required: true, message: "请输入短信验证码", trigger: "blur" },
          { validator: validateNumber },
        ],
        password: [
          { required: true, message: "请输入指令密码", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "密码长度为6-20位",
            trigger: "blur",
          },
          { validator: validateNoChinese },
        ],
      },

      showCountDown: true, //显示倒计时
      countDown: "", //倒计时一分钟
      intervalId: null, //定时器
    };
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        if (this.pageType) {
          // 控制面板进来
          if (this.statusInfo.cmdPasswordState) {
            this.current = "password";
            this.title = "指令密码";
          } else {
            this.current = "edit";
            this.title = "设置密码";
          }
        } else {
          // 设备详情进来
          if (this.statusInfo.cmdPasswordState) {
            if (this.handleType === "view") {
              this.current = "";
              this.title = "短信验证";
            } else if (this.handleType === "edit") {
              this.current = "edit";
              this.title = "编辑密码";
            }
          } else {
            this.current = "edit";
            this.title = "设置密码";
          }
        }
      }
    },
  },
  computed: {
    ...mapState(["user"]),
  },
  mounted() {
    this.addForm.mobile = this.user.mobile;
  },
  methods: {
    // 获取密码
    async getUtdQueryPassword() {
      let res = await reqUtdQueryPassword({
        tenantId: this.user.tenantId,
        deviceCode: this.deviceInfo.imei,
        mobile: this.addForm.mobile,
        code: this.addForm.smsCode,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.current = "show";
      this.title = "查看密码";
      this.addForm.password = res.data.password;
      this.$modal.notifySuccess("成功");
    },

    // 点击获取短信验证码
    async smsCodeClick() {
      if (!this.addForm.mobile)
        return this.$modal.notifyWarning("请输入手机号");
      if (this.addForm.mobile.length < 11)
        return this.$modal.notifyWarning("手机号码为11位数字");
      if (!this.showCountDown) return; //60s内只需发一次验证码

      // 发送验证码
      let res = await getSmsCode({
        mobile: this.addForm.mobile,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifyWarning("请注意查收手机短信验证码");
      this.showCountDown = false;
      this.countDown = 60;
      this.intervalId && clearInterval(this.intervalId);
      this.intervalId = setInterval(() => {
        if (this.countDown > 0 && this.countDown <= 60) {
          this.countDown--;
        } else {
          this.showCountDown = true;
          clearInterval(this.intervalId);
          this.intervalId = null;
        }
      }, 1000);
    },

    // 点击编辑
    onEdit() {
      this.current = "edit";
      this.title = "编辑密码";

      this.addForm.smsCode = "";

      this.showCountDown = true;
      this.countDown = 60;
      this.intervalId && clearInterval(this.intervalId);
    },

    // 点击绑定
    submit() {
      this.$refs.refForm.validate(async (valid) => {
        if (!valid) return;

        if (this.pageType) {
          // 控制面板进来
          if (this.statusInfo.cmdPasswordState) {
            // 已设置有密码，需下发指令
            this.keyCommandSendFoo();
          } else {
            // 未设置密码，需设置密码
            const res = await reqUtdSetPassword({
              deviceCode: this.deviceInfo.imei,
              password: this.addForm.password,
              mobile: this.addForm.mobile,
              code: this.addForm.smsCode,
            });
            if (res.code !== 20000)
              return this.$modal.notifyWarning(res.message);
            this.$modal.notifySuccess("设置成功");
            this.$emit("update");

            // 第一次设置密码,询问是否下发指令
            const result = await this.$confirm(
              `是否下发 ${this.commandInfo.keyName} 指令?`,
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }
            ).catch(() => {});
            if (result !== "confirm") return;
            this.keyCommandSendFoo(true);
          }
        } else {
          // 设备详情进来
          if (this.statusInfo.cmdPasswordState) {
            // 已设置有密码
            if (this.handleType === "view" && this.current !== "edit") {
              this.getUtdQueryPassword();
            } else {
              this.utdSetPasswordFoo();
            }
          } else {
            // 未设置密码，需设置密码
            this.utdSetPasswordFoo();
          }
        }
      });
    },

    async utdSetPasswordFoo() {
      let res = await reqUtdSetPassword({
        deviceCode: this.deviceInfo.imei,
        password: this.addForm.password,
        mobile: this.addForm.mobile,
        code: this.addForm.smsCode,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("设置成功");
      this.$emit("update");
      this.closeDialog();
    },

    async keyCommandSendFoo(isCloseDialog = false) {
      let res = await reqKeyCommandSend({
        deviceCode: this.deviceInfo.imei || this.deviceInfo.deviceCode,
        id: this.commandInfo.id,
        password: this.addForm.password,
      });
      if (res.code !== 20000) {
        if (isCloseDialog) {
          this.closeDialog();
        }
        this.$modal.notifyWarning(res.message);
        return;
      }
      this.$modal.notifySuccess("指令下发成功");

      this.$emit("update");
      this.closeDialog();
    },

    // 点击关闭弹框
    closeDialog() {
      this.$refs.refForm.resetFields();

      this.showCountDown = true;
      this.countDown = 60;
      this.intervalId && clearInterval(this.intervalId);

      setTimeout(() => {
        this.current = "";
        this.title = "短信验证";
      }, 500);

      this.addForm.smsCode = this.addForm.password = "";

      this.dialogVisible = false;
    },

    // 获取焦点
    onFocus(event) {
      setTimeout(function () {
        event.target.readOnly = false;
      }, 100);
    },
    // 失去焦点
    onBlur(event) {
      event.target.readOnly = true;
    },
    // 防止内容删完时出现账号和密码
    onInput(event, val) {
      if (val.length === 0) {
        this.onBlur(event);
        this.onFocus(event);
      }
    },
    // 防止多次点击时出现账号和密码
    onMousedown(event) {
      this.onBlur(event);
      this.onFocus(event);
    },
  },
};
</script>

<style lang="less" scoped>
@import url("../../../../views/common.less");
// input后面的查询按钮
::v-deep .el-input-group__append {
  color: #fff;
  border: none;
  background-color: #7367f0;
}

.tip {
  color: #999;
  font-size: 12px;
  line-height: 22px;
  padding-left: 30px;
  .label {
  }
}
</style>
